package cn.dyw.cloudmusic.utils;

import cn.dyw.cloudmusic.config.ParamsConfig;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.Security;
import java.security.spec.RSAPublicKeySpec;

/**
 * @author: dyw770
 * @Date: 2018/12/9 16:26
 * @Description: RSA加密
 */
public class RSAUtils{

    /**
     * encSecKey 生成
     * @param i
     * @return
     * @throws Exception
     */
    public static String encSecKey(String i) throws Exception {

        i = StringUtils.reverse(i);

        BigInteger b1 = new BigInteger(ParamsConfig.f, 16);
        BigInteger b2 = new BigInteger(ParamsConfig.e, 16);
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec publicKey = new RSAPublicKeySpec(b1, b2);

        // 对数据加密
        Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(publicKey));
        // 返回十六进制结果
        byte[] s = cipher.doFinal(i.getBytes("UTF-8"));
        return bytesToHexString(s);
    }

    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
